<template>
  <el-dialog title="绑定资源（策略组权限的单独补充）" v-model="dialogVisible" width="1200px">
    <div v-loading="loading" style="position: relative;">
      <el-button type="primary" size="small" plain @click="handleSave" class="save-btn">保存({{nameMapping[activeTab]}})</el-button>
      <el-tabs v-if="!loading" v-model="activeTab" @tab-change="handleClick">
        <el-tab-pane label="站点权限" name="0">
          <CoordinateSelector v-if="activeTab == 0" ref="coordinateRef" :resourceList="siteList" resourceTitle="站点名称" :authList="authList" :checkedList="typeCheckedList" :disabledList="typeDisabledList" />
        </el-tab-pane>
        <el-tab-pane label="栏目权限" name="1">
          <CoordinateSelector v-if="activeTab == 1" ref="coordinateRef" :resourceList="categoryList" resourceTitle="栏目名称" :authList="authList" :checkedList="typeCheckedList" :disabledList="typeDisabledList" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed, onMounted } from 'vue'
import { getUserResourceAuth, bindUserResourceAuth, selectResourceAuthByUserId, getAllCategory, getWebStation, getAuthList } from '@/api/strategy'
import { ElMessage } from 'element-plus'
import { createTreeData } from '@ruifox-cms/utils'
import { useStore } from 'vuex'
import CoordinateSelector from './CoordinateSelector'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  userId: {
    type: [Number, String],
    default: ''
  }
})
const emit = defineEmits(['update:show'])
const store = useStore()
const loading = ref(true)
const dialogVisible = computed({
  get() {
    return props.show
  },
  set(val) {
    emit('update:show', val)
  }
})
watch(dialogVisible, val => {
  dialogVisible.value = val
  if (val) {
    handleGetUserResourceAuth()
  }
})
// 查询用户的策略组拥有的权限
const disabledList = ref([])
const typeDisabledList = ref([])
const handleGetDisabledList = async () => {
  const res = await selectResourceAuthByUserId({ userId: props.userId })
  if (res.code === 20000) {
    disabledList.value = res.data
    typeDisabledList.value = disabledList.value.filter(item => item.type == activeTab.value)
  }
  loading.value = false
}
// 查询用户已分配资源
const checkedList = ref([])
const typeCheckedList = ref([])
const handleGetUserResourceAuth = async () => {
  const res = await getUserResourceAuth({ userId: props.userId })
  if (res.code === 20000) {
    checkedList.value = res.data
    typeCheckedList.value = checkedList.value.filter(item => item.type == activeTab.value)
  }
  loading.value = false
}

const activeTab = ref('0')
const nameMapping = {
  '0': '站点权限',
  '1': '栏目权限'
}
const handleClick = (val) => {
  activeTab.value = val
}
watch(activeTab, (val) => {
  typeCheckedList.value = checkedList.value.filter(item => item.type == val)
  typeDisabledList.value = disabledList.value.filter(item => item.type == val)
})

const authList = ref([])
const handleGetAuthList = async () => {
  const res = await getAuthList()
  if (res.code === 20000) {
    authList.value = res.data
  }
}
/*********************************************************站点权限***************************************************/
const siteList = ref([])
const handleGetWebStation = async () => {
  let res = await getWebStation({ groupId: store.state.base.userInfo.groupId })
  if (res.code == 20000) {
    siteList.value = res.data
  }
}
/*********************************************************栏目权限***************************************************/
const categoryList = ref([])
const handleGetAllCategory = async () => {
  let res = await getAllCategory()
  categoryList.value = createTreeData(res.data)
}

// 保存设置
const coordinateRef = ref(null)
const handleSave = async () => {
  const data = coordinateRef.value.getSelectedData()
  const res = await bindUserResourceAuth({
    userId: props.userId,
    resourceAuthList: data,
    type: activeTab.value
  })
  if (res.code === 20000) {
    ElMessage.success('更新成功')
    handleGetUserResourceAuth()
  }
}

onMounted(async () => {
  await handleGetAuthList()
  await handleGetWebStation()
  await handleGetAllCategory()
  await handleGetDisabledList()
  await handleGetUserResourceAuth()
})
</script>

<style lang="scss" scoped>
.save-btn {
  position: absolute;
  right: 0;
  top: 5px;
  z-index: 999;
}
</style>
